package com.lingyi.carmanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyi.carmanagement.pojo.Car;
import com.lingyi.carmanagement.pojo.Cartype;
import com.lingyi.carmanagement.service.CarService;
import com.lingyi.carmanagement.service.CartypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auth 吴阳基
 * @date 2024/2/16 11:35
 */
@Controller
@RequestMapping("/car")
public class CarController {
	@Autowired
	private CarService carService;
	
	@Autowired
	private CartypeService cartypeService;
	
	@GetMapping("/toAdd")
	public String toAdd(Model model) {
		
		List<Cartype> cartypes = cartypeService.list();
		
		model.addAttribute("cartypes",cartypes);
		
		return "add";
	}
	
	@PostMapping("/add")
	public String add(Car car) {
		boolean result = carService.save(car);
		if (result) {
			return "redirect:/car/list";
		}
		return "add";
	}
	
	
	@GetMapping("/list")
	public String list(Model model,
	                   Car car,
	                   @RequestParam(defaultValue = "1") Integer pageNo) {
		Integer pageSize = 3;
		
		IPage<Car> page = new Page<>(pageNo, pageSize);
		
		QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
		
		if (car.getCarType() != null && car.getCarType() > 0) {
			queryWrapper.eq("carType", car.getCarType());
		}
		if (car.getCarName() != null && car.getCarName() != "") {
			queryWrapper.like("carName", car.getCarName());
		}
		
		IPage<Car> resultPage = carService.page(page, queryWrapper);
		List<Car> list = resultPage.getRecords();
		
		// 总记录数
		int totalCount = (int) resultPage.getTotal();
		// 总页数
		int totalPages = (int) resultPage.getPages();
		
		List<Cartype> cartypes = cartypeService.list(null);
		
		model.addAttribute("cartypes", cartypes);
		model.addAttribute("list", list);
		model.addAttribute("resultPage", resultPage);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("totalPages", totalPages);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("pageSize", pageSize);
		return "list";
	}
	
	@GetMapping("/selectById")
	public String selectById(Model model, Integer id) {
		
		Car edocEntry = carService.getById(id);
		
		List<Cartype> cartypes = cartypeService.list();
		
		model.addAttribute("cartypes",cartypes);
		
		model.addAttribute("ed", edocEntry);
		
		return "update";
	}
	
	@PostMapping("/update")
	public String update(Car car) {
		
		boolean result = carService.updateById(car);
		
		if (result) {
			return "redirect:/car/list";
		}
		return "update";
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public boolean del(Integer id) {
		
		return carService.removeById(id);
		
	}
}
